package com.app;

import java.awt.BorderLayout;
import java.awt.Event;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowFocusListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Date;
import java.util.List;

import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTable;
import javax.swing.KeyStroke;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;

import com.db.processror.TradeProcessor;
import com.trade.TradeBean;

public class TradeReconciler implements MouseListener {

	private JFrame jFrame = null;
	private JPanel jContentPane = null;
	private JMenuBar jJMenuBar = null;
	private JMenu fileMenu = null;
	private JMenu editMenu = null;
	private JMenu adminMenu = null;
	private JMenu helpMenu = null;

	private JMenuItem exitMenuItem = null;
	private JMenuItem aboutMenuItem = null;
	private JMenuItem cutMenuItem = null;
	private JMenuItem dropTableMenuItem = null;
	private JMenuItem createReconcileTableMenuItem = null;
	private JMenuItem loadTableMenuItem = null;
	private JMenuItem loadTableFileMenuItem = null;
	private JMenuItem copyMenuItem = null;
	private JMenuItem pasteMenuItem = null;
	private JMenuItem saveMenuItem = null;
	private JMenuItem reportMenuItem = null;
	private JMenuItem insertTradeMenuItem = null;
	private JDialog aboutDialog = null;
	private JPanel aboutContentPane = null;
	private JLabel aboutVersionLabel = null;
	private JLabel tradeCountLabel = null;
	private JTable tradeTable = null;

	
	
	/**
	 * This method initializes jFrame
	 * 
	 * @return javax.swing.JFrame
	 */
	private JFrame getJFrame() {
		if (jFrame == null) {
			jFrame = new JFrame();
			jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
			jFrame.setJMenuBar(getJJMenuBar());
			jFrame.setSize(640, 480);
			jFrame.setContentPane(getJContentPane());
			jFrame.setTitle("Trade Reconciler");
		}
		return jFrame;
	}

	/**
	 * This method initializes jContentPane
	 * 
	 * @return javax.swing.JPanel
	 */
	private JPanel getJContentPane() {
		if (jContentPane == null) {
			jContentPane = new JPanel();
			jContentPane.setLayout(new BorderLayout());
			tradeTable = getTradeTable();
			tradeTable.removeColumn(tradeTable.getColumn("OrderRef"));
			tradeTable.removeColumn(tradeTable.getColumn("Settlement"));
			tradeTable.removeColumn(tradeTable.getColumn("Segment"));
			tradeTable.removeColumn(tradeTable.getColumn("Exchange"));
			tradeTable.removeColumn(tradeTable.getColumn("DPIdClientDPId"));
			jContentPane.add(new JScrollPane(tradeTable), BorderLayout.NORTH);
			jContentPane.add(new JSeparator(SwingConstants.HORIZONTAL));
			jContentPane.add(getTradeCountLabel(), BorderLayout.SOUTH);
		}
		return jContentPane;
	}

	private JLabel getTradeCountLabel() {
		tradeCountLabel = new JLabel();
		tradeCountLabel.setText("Trade Count = "
				+ tradeTable.getModel().getRowCount());
		return tradeCountLabel;
	}

	/**
	 * This method initializes jJMenuBar
	 * 
	 * @return javax.swing.JMenuBar
	 */
	private JMenuBar getJJMenuBar() {
		if (jJMenuBar == null) {
			jJMenuBar = new JMenuBar();
			jJMenuBar.add(getFileMenu());
			jJMenuBar.add(getEditMenu());
			jJMenuBar.add(getAdminMenu());
			jJMenuBar.add(getHelpMenu());
		}
		return jJMenuBar;
	}

	/**
	 * This method initializes jMenu
	 * 
	 * @return javax.swing.JMenu
	 */
	private JMenu getFileMenu() {
		if (fileMenu == null) {
			fileMenu = new JMenu();
			fileMenu.setText("File");
			fileMenu.add(getSaveMenuItem());
			fileMenu.add(getExitMenuItem());
		}
		return fileMenu;
	}

	/**
	 * This method initializes jMenu
	 * 
	 * @return javax.swing.JMenu
	 */
	private JMenu getEditMenu() {
		if (editMenu == null) {
			editMenu = new JMenu();
			editMenu.setText("Edit");
			editMenu.add(getCutMenuItem());
			editMenu.add(getCopyMenuItem());
			editMenu.add(getPasteMenuItem());
		}
		return editMenu;
	}

	private JMenu getAdminMenu() {
		if (adminMenu == null) {
			adminMenu = new JMenu();
			adminMenu.setText("Admin");
			adminMenu.add(getDropTableMenuItem());
			adminMenu.add(getLoadTableMenuItem());
			adminMenu.add(getLoadTableFileMenuItem());
			adminMenu.add(getCreateReconcileTableMenuItem());
			adminMenu.add(getReportMenuItem());
			adminMenu.add(getInsertTradeMenuItem());
		}
		return adminMenu;
	}

	/**
	 * This method initializes jMenu
	 * 
	 * @return javax.swing.JMenu
	 */
	private JMenu getHelpMenu() {
		if (helpMenu == null) {
			helpMenu = new JMenu();
			helpMenu.setText("Help");
			helpMenu.add(getAboutMenuItem());
		}
		return helpMenu;
	}

	/**
	 * This method initializes jMenuItem
	 * 
	 * @return javax.swing.JMenuItem
	 */
	private JMenuItem getExitMenuItem() {
		if (exitMenuItem == null) {
			exitMenuItem = new JMenuItem();
			exitMenuItem.setText("Exit");
			exitMenuItem.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					System.out.println("i am going to exit");
					System.exit(0);
				}
			});
		}
		return exitMenuItem;
	}

	/**
	 * This method initializes jMenuItem
	 * 
	 * @return javax.swing.JMenuItem
	 */
	private JMenuItem getAboutMenuItem() {
		if (aboutMenuItem == null) {
			aboutMenuItem = new JMenuItem();
			aboutMenuItem.setText("About");
			aboutMenuItem.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					JDialog aboutDialog = getAboutDialog();
					aboutDialog.pack();
					Point loc = getJFrame().getLocation();
					loc.translate(20, 20);
					aboutDialog.setLocation(loc);
					aboutDialog.setVisible(true);
				}
			});
		}
		return aboutMenuItem;
	}

	/**
	 * This method initializes aboutDialog
	 * 
	 * @return javax.swing.JDialog
	 */
	private JDialog getAboutDialog() {
		if (aboutDialog == null) {
			aboutDialog = new JDialog(getJFrame(), true);
			aboutDialog.setTitle("About");
			aboutDialog.setContentPane(getAboutContentPane());
		}
		return aboutDialog;
	}

	/**
	 * This method initializes aboutContentPane
	 * 
	 * @return javax.swing.JPanel
	 */
	private JPanel getAboutContentPane() {
		if (aboutContentPane == null) {
			aboutContentPane = new JPanel();
			aboutContentPane.setLayout(new BorderLayout());
			aboutContentPane.add(getAboutVersionLabel(), BorderLayout.CENTER);
		}
		return aboutContentPane;
	}

	/**
	 * This method initializes aboutVersionLabel
	 * 
	 * @return javax.swing.JLabel
	 */
	private JLabel getAboutVersionLabel() {
		if (aboutVersionLabel == null) {
			aboutVersionLabel = new JLabel();
			aboutVersionLabel.setText("Trade Reconciler\nVersion 1.0");
			aboutVersionLabel.setHorizontalAlignment(SwingConstants.CENTER);
		}
		return aboutVersionLabel;
	}

	/**
	 * This method initializes jMenuItem
	 * 
	 * @return javax.swing.JMenuItem
	 */
	private JMenuItem getCutMenuItem() {
		if (cutMenuItem == null) {
			cutMenuItem = new JMenuItem();
			cutMenuItem.setText("Cut");
			cutMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X,
					Event.CTRL_MASK, true));
		}
		return cutMenuItem;
	}

	private JMenuItem getDropTableMenuItem() {
		if (dropTableMenuItem == null) {
			dropTableMenuItem = new JMenuItem();
			dropTableMenuItem.setText("Drop Table");
			dropTableMenuItem.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					System.out.println("came here to drop");
					TradeProcessor tp = new TradeProcessor();
					try {
						tp.dropTable();
						// jContentPane.remove(jContentPane.getComponent(0));
						// tradeTable = null;
						// jContentPane.add(new JScrollPane(getTradeTable()));
						// jContentPane.repaint();
						int rows = tradeTable.getModel().getRowCount();
						for (int i = 0; i < rows; i++) {
							((DefaultTableModel) tradeTable.getModel())
									.removeRow(0);
						}
						tradeCountLabel.setText("Trade Count = "
								+ tradeTable.getModel().getRowCount());
						System.out.println("after updating rowcount="
								+ tradeTable.getModel().getRowCount());
						jContentPane.repaint();
						SwingUtilities.updateComponentTreeUI(jContentPane);
					} catch (Exception e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
				}
			});
			dropTableMenuItem.setAccelerator(KeyStroke.getKeyStroke(
					KeyEvent.VK_D, Event.CTRL_MASK, true));
		}
		return dropTableMenuItem;
	}

	private JMenuItem getCreateReconcileTableMenuItem() {
		if (createReconcileTableMenuItem == null) {
			createReconcileTableMenuItem = new JMenuItem();
			createReconcileTableMenuItem.setText("Create Reconcile Table");
			createReconcileTableMenuItem
					.addActionListener(new ActionListener() {
						public void actionPerformed(ActionEvent e) {
							TradeProcessor tp = new TradeProcessor();
							try {
								tp.createReconcileTable();
							} catch (Exception e1) {
								// TODO Auto-generated catch block
								e1.printStackTrace();
							}
							tp.shutdownDB();
						}
					});
			createReconcileTableMenuItem.setAccelerator(KeyStroke.getKeyStroke(
					KeyEvent.VK_C, Event.CTRL_MASK, true));
		}
		return createReconcileTableMenuItem;
	}

	private JMenuItem getLoadTableMenuItem() {
		if (loadTableMenuItem == null) {
			loadTableMenuItem = new JMenuItem();
			loadTableMenuItem.setText("Load Table");
			loadTableMenuItem.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					System.out.println("came here to load");
					TradeProcessor tp = new TradeProcessor();
					try {
						tp.loadTable();
						tradeTable.setModel(getTradeTable().getModel());
						tradeTable.removeColumn(tradeTable.getColumn("OrderRef"));
						tradeTable.removeColumn(tradeTable.getColumn("Settlement"));
						tradeTable.removeColumn(tradeTable.getColumn("Segment"));
						tradeTable.removeColumn(tradeTable.getColumn("Exchange"));
						tradeTable.removeColumn(tradeTable.getColumn("DPIdClientDPId"));
						tradeCountLabel.setText("Trade Count = "
								+ tradeTable.getModel().getRowCount());
						// jContentPane.remove(jContentPane.getComponent(0));
						// tradeTable = null;
						// jContentPane.add(new JScrollPane(getTradeTable()));
						jContentPane.repaint();
						SwingUtilities.updateComponentTreeUI(jContentPane);
					} catch (Exception e1) {
						e1.printStackTrace();
					}

				}
			});
			loadTableMenuItem.setAccelerator(KeyStroke.getKeyStroke(
					KeyEvent.VK_L, Event.CTRL_MASK, true));
		}
		if (tradeTable != null) {
			tradeTable.setRowSelectionAllowed(true);
			tradeTable.setAutoCreateRowSorter(true);
			tradeTable.addMouseListener(this);
		}

		return loadTableMenuItem;
	}

	private JMenuItem getReportMenuItem() {
		if (reportMenuItem == null) {
			reportMenuItem = new JMenuItem();
			reportMenuItem.setText("Generate Report");
			reportMenuItem.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					System.out.println("generating report");
					generateReport();
				}
			});
			reportMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R,
					Event.CTRL_MASK, true));
		}
		return reportMenuItem;
	}
	
	private JMenuItem getInsertTradeMenuItem() {
		if (insertTradeMenuItem == null) {
			insertTradeMenuItem = new JMenuItem();
			insertTradeMenuItem.setText("Insert Trade");
			insertTradeMenuItem.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					System.out.println("Inserting Trade");
					InsertTrade it = new InsertTrade();
					it.pack();
					it.setVisible(true);
				}
			});
			insertTradeMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_I,
					Event.CTRL_MASK, true));
		}
		return insertTradeMenuItem;
	}

	private void generateReport() {
		TradeProcessor tp = new TradeProcessor();
		tp.generateReport();
	}

	private JMenuItem getLoadTableFileMenuItem() {
		if (loadTableFileMenuItem == null) {
			loadTableFileMenuItem = new JMenuItem();
			loadTableFileMenuItem.setText("Load Table File...");
			loadTableFileMenuItem.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					System.out.println("came here to load");
					JFileChooser fc = new JFileChooser(".");

					int returnVal = fc.showOpenDialog(jContentPane);
					if (returnVal == JFileChooser.APPROVE_OPTION) {
						File file = fc.getSelectedFile();
						// This is where a real application would open the file.
						try {
							System.out.println("Opening: "
									+ file.getCanonicalPath() + ".");

							TradeProcessor tp = new TradeProcessor();
							try {
								tp.loadTableFile(file.getCanonicalFile());
								tradeTable.setModel(getTradeTable().getModel());
								tradeTable.removeColumn(tradeTable.getColumn("OrderRef"));
								tradeTable.removeColumn(tradeTable.getColumn("Settlement"));
								tradeTable.removeColumn(tradeTable.getColumn("Segment"));
								tradeTable.removeColumn(tradeTable.getColumn("Exchange"));
								tradeTable.removeColumn(tradeTable.getColumn("DPIdClientDPId"));
								tradeCountLabel.setText("Trade Count = "
										+ tradeTable.getModel().getRowCount());

								// jContentPane.remove(jContentPane
								// .getComponent());
								// tradeTable = null;
								// jContentPane.add(new JScrollPane(
								// getTradeTable()));
								// tradeTable.removeColumn(tradeTable
								// .getColumn("Date"));
								// jContentPane.repaint();
								SwingUtilities
										.updateComponentTreeUI(jContentPane);
							} catch (Exception e1) {
								e1.printStackTrace();
							}
						} catch (IOException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}

					} else {
						System.out.println("Open command cancelled by user.");
					}

				}
			});
			loadTableFileMenuItem.setAccelerator(KeyStroke.getKeyStroke(
					KeyEvent.VK_K, Event.CTRL_MASK, true));
			if (tradeTable != null) {
				tradeTable.setRowSelectionAllowed(true);
				tradeTable.setAutoCreateRowSorter(true);
				tradeTable.addMouseListener(this);
			}
		}
		return loadTableFileMenuItem;
	}

	/**
	 * This method initializes jMenuItem
	 * 
	 * @return javax.swing.JMenuItem
	 */
	private JMenuItem getCopyMenuItem() {
		if (copyMenuItem == null) {
			copyMenuItem = new JMenuItem();
			copyMenuItem.setText("Copy");
			copyMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C,
					Event.CTRL_MASK, true));
		}
		return copyMenuItem;
	}

	/**
	 * This method initializes jMenuItem
	 * 
	 * @return javax.swing.JMenuItem
	 */
	private JMenuItem getPasteMenuItem() {
		if (pasteMenuItem == null) {
			pasteMenuItem = new JMenuItem();
			pasteMenuItem.setText("Paste");
			pasteMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V,
					Event.CTRL_MASK, true));
		}
		return pasteMenuItem;
	}

	/**
	 * This method initializes jMenuItem
	 * 
	 * @return javax.swing.JMenuItem
	 */
	private JMenuItem getSaveMenuItem() {
		if (saveMenuItem == null) {
			saveMenuItem = new JMenuItem();
			saveMenuItem.setText("Save");
			saveMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,
					Event.CTRL_MASK, true));
		}
		return saveMenuItem;
	}

	/**
	 * This method initializes tradeTable
	 * 
	 * @return javax.swing.JTable
	 */
	private JTable getTradeTable() {
		TradeProcessor tp = new TradeProcessor();

		List<TradeBean> trades = null;
		try {
			trades = tp.getSellTrades();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Field[] f = TradeBean.class.getDeclaredFields();
		Method[] m = new Method[f.length];

		String[] columnNames = new String[f.length];
		for (int i = 0; i < f.length; i++) {
			columnNames[i] = f[i].getName();
		}

		// Set the column headers
		for (int i = 0; i < f.length; i++) {
			// tradeTable.getColumnModel().getColumn(i).setHeaderValue(f[i].getName());
			// Fetch the getters using reflection
			try {
				m[i] = TradeBean.class.getDeclaredMethod(
						"get" + f[i].getName(), new Class[0]);
				System.out.println(m[i].getName());
			} catch (SecurityException e) {
				e.printStackTrace();
			} catch (NoSuchMethodException e) {
				e.printStackTrace();
			}
		}
		Object[][] data = new Object[trades.size()][f.length + 1];
		// Set the values in the tables for view
		for (int i = 0; i < trades.size(); i++) {
			for (int j = 0; j < m.length; j++) {
				try {
					// use reflection to invoke the getters
					data[i][j] = m[j].invoke(trades.get(i), new Object[0]);
				} catch (IllegalArgumentException e) {
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					e.printStackTrace();
				}
			}
		}
		DefaultTableModel dtm = new DefaultTableModel(data, columnNames);

		JTable tempTradeTable = new JTable(dtm) {
			private static final long serialVersionUID = 133833919444295084L;

			public boolean isCellEditable(int row, int column) {
				return false;
			}
		};

		tempTradeTable.setRowSelectionAllowed(true);
		tempTradeTable.setAutoCreateRowSorter(true);
		tempTradeTable.addMouseListener(this);
		return tempTradeTable;
	}

	/**
	 * Launches this application
	 */
	public static void main(String[] args) {
		PrintStream ps=null;
		try {
			ps = new PrintStream(new File("trader.log"));
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
//		System.setOut(ps);
//		System.setErr(ps);
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				TradeReconciler application = new TradeReconciler();
				application.getJFrame().pack();
				application.getJFrame().setSize(840, 500);
				Point p = application.getJFrame().getLocation();
				p.translate(100, 100);
				application.getJFrame().setLocation(p);
				application.getJFrame().setVisible(true);
				application.getJFrame().addWindowFocusListener(
						application.new MyWindowListener());

			}
		});
	}

	class MyWindowListener implements WindowFocusListener {

		@Override
		public void windowGainedFocus(WindowEvent e) {
			tradeCountLabel.setText("Trade Count = "
					+ tradeTable.getModel().getRowCount());
			System.out.println("window gained focus");

		}

		@Override
		public void windowLostFocus(WindowEvent e) {
			System.out.println(" lost focus");
		}

	}

	@Override
	public void mouseClicked(MouseEvent e) {
		if(e.getButton() == MouseEvent.BUTTON3){
			System.out.println("right click");			
		}
		
		if (e.getClickCount() == 2 && e.getButton() == MouseEvent.BUTTON1) {

			TradeBean tb = new TradeBean();

			tb.setTradeID((Long) tradeTable.getModel().getValueAt(
					tradeTable.convertRowIndexToModel(tradeTable
							.getSelectedRow()), 0));
			tb.setDate((Date) tradeTable.getModel().getValueAt(
					tradeTable.convertRowIndexToModel(tradeTable
							.getSelectedRow()), 1));
			tb.setStock((String) tradeTable.getModel().getValueAt(
					tradeTable.convertRowIndexToModel(tradeTable
							.getSelectedRow()), 2));
			tb.setQty((Integer) tradeTable.getModel().getValueAt(
					tradeTable.convertRowIndexToModel(tradeTable
							.getSelectedRow()), 4));
			System.out.println("double click date="
					+ tradeTable.getModel().getValueAt(
							tradeTable.convertRowIndexToModel(tradeTable
									.getSelectedRow()), 1));
			// TradeSelector ts = new TradeSelector(tb);
			TradeSelector ts = new TradeSelector(tb, tradeTable);
			ts.pack();
			
			if (ts.getBuyCount() == 0) {
				ts.dispose();
				java.awt.EventQueue.invokeLater(new Runnable() {
					public void run() {
						NoData dialog = new NoData(new javax.swing.JFrame(),
								true);
						dialog
								.addWindowListener(new java.awt.event.WindowAdapter() {
									public void windowClosing(
											java.awt.event.WindowEvent e) {
										System.exit(0);
									}
								});
						dialog.setVisible(true);
					}
				});

			} else {
				ts.setVisible(true);
			}
			tradeCountLabel.setText("Trade Count = "
					+ tradeTable.getModel().getRowCount());
			
		}

	}

	@Override
	public void mouseEntered(MouseEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mouseExited(MouseEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mousePressed(MouseEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mouseReleased(MouseEvent e) {
		// TODO Auto-generated method stub

	}
	

	
}
